package com.sk.weichat.ui.me;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.Code;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.EditBaseActivity;

import com.sk.weichat.util.LiveDataBus;
import com.sk.weichat.util.LiveDataTimer;
import com.sk.weichat.util.ToastUtil;

import com.sk.weichat.view.RoundRectInputEditText;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

public class SmsCodeForIdentifyActivity extends EditBaseActivity {

    public final static int code_success = 76821;

    private RoundRectInputEditText roundRectInputEditText;
    private TextView tvTips;
    private Button btnSend;
    private LiveDataTimer liveDataTimer = new LiveDataTimer();


    private String event = "";

    public static void startSmsCodeForIdentifyActivity(String event, Context context) {
        Intent intent = new Intent(context, SmsCodeForIdentifyActivity.class);
        intent.putExtra("event", event);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms_code_for_identify);
        getSupportActionBar().hide();
        event = getIntent() != null ? getIntent().getStringExtra("event") : "";
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = findViewById(R.id.tv_title_center);
        tvTitle.setText(getResources().getString(R.string.title_sms_code_for_identify));
        btnSend = findViewById(R.id.btn_send);
        btnSend.setEnabled(false);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               sendCode();
            }
        });
        tvTips = findViewById(R.id.tv_tips_phone);
        //tvTips.setText(getResources().getString(R.string.title_send_sms_code_to));
        roundRectInputEditText = findViewById(R.id.edt_code);
        roundRectInputEditText.setTextWatcher(new Observer<CharSequence>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(CharSequence charSequence) {
                if (charSequence.length() == 4) {
                    checkSms(charSequence.toString());
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
        //倒计时结束后才可进行下一次发送验证码
        if (!liveDataTimer.isRunning()) {
           sendCode();
        }
        //弹出键盘输入
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        initTimer();
    }

    private void initTimer() {
        liveDataTimer.setEndTime(60);
        liveDataTimer.setStartTime(0);
        liveDataTimer.getTime().observe(this, new android.arch.lifecycle.Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer integer) {
                if (integer > 0 && integer <= 60) {
                    btnSend.setEnabled(false);
                    btnSend.setTextColor(mContext.getResources().getColor(R.color.white));
                    btnSend.setBackgroundResource(R.drawable.shape_corner_26_solid_gray_bdc2c8);
                    btnSend.setText(mContext.getString(R.string.send_again) + " (" + (60 - integer) + ")");
                } else {
                    btnSend.setTextColor(mContext.getResources().getColor(R.color.white));
                    btnSend.setBackgroundResource(R.drawable.shape_corner_26dp_solid_primary);
                    btnSend.setEnabled(true);
                    btnSend.setText(mContext.getString(R.string.send_again));
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        liveDataTimer.stop();
        super.onDestroy();
    }


    public void sendCodeResult(ObjectResult<Code> result) {
        if (result.getResultCode() == 1) {
            liveDataTimer.start();
            tvTips.setText(getResources().getString(R.string.title_send_sms_code_to) + " +" + AppConstant.areaCode + " " + coreManager.getSelf().getPhone());
        } else {
            String message = TextUtils.isEmpty(result.getResultMsg()) ? getResources().getString(R.string.title_send_sms_code_error) : result.getResultMsg();
            showLoadFailMsg(message);
        }
    }


    public void checkSmsResult(ObjectResult<String> result) {
        if (result.getResultCode() == 1) {
            setResult(Activity.RESULT_OK);
            System.out.println("livedata:"+event);
            LiveDataBus.get().with(event,Integer.class).setValue(code_success);
            finish();
        } else {
            roundRectInputEditText.setText("");
            showLoadFailMsg(result.getResultMsg());
        }
    }


    public void showProgress() {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(this);
        }
    }


    public void hideProgress() {
        DialogHelper.dismissProgressDialog();
    }


    public void showLoadFailMsg(String err) {
        ToastUtil.showToast(mContext, err);
    }


    /**
     * 发送验证码
     */
    public void sendCode() {
        showProgress();
        Map<String, String> params = new HashMap<>();
        String language = Locale.getDefault().getLanguage();
        params.put("language", language);
        params.put("areaCode", AppConstant.areaCode);
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        HttpUtils.post().url(coreManager.getConfig().SMS_FOR_RESET_PASSWORD)
                .params(params)
                .build()
                .execute(new BaseCallback<Code>(Code.class) {

                    @Override
                    public void onResponse(ObjectResult<Code> result) {
                        sendCodeResult(result);
                        hideProgress();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        Log.e("sendCode", "Exception", e);
                        showLoadFailMsg(e.toString());
                        hideProgress();
                    }
                });
    }

    /**
     * 验证短信验证码是否正确
     */
    public void checkSms(String code) {
        showProgress();
        Map<String, String> params = new HashMap<>();
        params.put("code", code);
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        HttpUtils.post().url(coreManager.getConfig().SMS_FOR_CHECK_PASSWORD)
                .params(params)
                .build()
                .execute(new BaseCallback<String>(String.class) {
                    @Override
                    public void onResponse(ObjectResult<String> result) {
                        checkSmsResult(result);
                        hideProgress();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        Log.e("checkSms", "Exception", e);
                        showLoadFailMsg(e.toString());
                        hideProgress();
                    }
                });
    }

}
